package com.mulanweb.handler.wechat;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSONObject;
import com.mulanweb.api.module.model.ChatHistory;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.*;

import static com.mulanweb.utils.StringFormatterUtil.enCodeString;
/**
 * Created by Administrator on 2017/2/22 0022.
 */
public class ServiceChatHistoryHandler {

    public static void grabServiceChatHistory(){
        /**
         * 获取客服聊天记录
         */
        String url = "https://api.weixin.qq.com/customservice/msgrecord/getmsglist?access_token=ACCESS_TOKEN".replace("ACCESS_TOKEN", TokenHandler.getAccessToken());
        Map<String, String> para = new HashMap<String, String>();
        Date current = new Date();
        para.put("msgid", "1");
        para.put("number", "80");
        Map<String, Object> test = new HashMap<String, Object>();
        List<Map> o = new ArrayList<Map>();
        boolean result = true;
        long i = 0;
        while (result && i<20 ) {
            i++;
            Long day =  24L * 60L * 60L;
            String startTime = (current.getTime() / 1000 - i*day ) + "";
            para.put("starttime", startTime);
            String endTime = current.getTime()/1000 - (i-1)*day+"";
            para.put("endtime", endTime);

            CloseableHttpClient client = null;
            CloseableHttpResponse resp = null;
            try {
                client = HttpClients.createDefault();
                HttpPost post = new HttpPost(url);
                post.addHeader("Content-type", "application/json");
                StringEntity entity = new StringEntity(JSONUtils.toJSONString(para), ContentType.create("application/json", "UTF-8"));
                post.setEntity(entity);
                resp = client.execute(post);
                int statusCode = resp.getStatusLine().getStatusCode();
                if (statusCode >= 200 && statusCode < 300) {
                    String str = EntityUtils.toString(resp.getEntity(), "utf-8");
                    test = JSONObject.parseObject(str);
                    o = (List<Map>) test.get("recordlist");
                    if (o.size() >0) {
                        for(Map map : o){
                            String openId = map.get("openid")+"";
                            String opercode = map.get("opercode")+"";
                            String text = enCodeString(map.get("text")+"");
                            String time = map.get("time")+"";
                            String worker = map.get("worker")+"";
                            ChatHistory chatHistory = ChatHistory.dao.findFirst("SELECT * FROM chat_history WHERE sent_time = ? AND chat_type = ?",time,opercode);
                            if(chatHistory !=null){
                                continue;
                            }
                            chatHistory = new ChatHistory();
                            chatHistory.setChatType(opercode);
                            chatHistory.setContent(text);
                            if("2002".equals(opercode)){
                                chatHistory.setToUserOpenid(openId);
                                chatHistory.setFromUseropenId(worker);
                            }else{
                                chatHistory.setToUserOpenid(worker);
                                chatHistory.setFromUseropenId(openId);
                            }
                            chatHistory.setSent_time(Long.parseLong(time));
                            chatHistory.setCreate_time(new Date());
                            chatHistory.save();
                        }
                    }else{
                        continue;
                    }
                } else {
                    //TODO 请求错误
                    String str = EntityUtils.toString(resp.getEntity(),"utf-8");
                    System.out.println(str);
                }
            } catch (Exception ioe) {
                result = false;
                ioe.printStackTrace();
            } finally {
                try {
                    client.close();
                    resp.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
